import tkinter as tk
from tkinter import filedialog
import requests
import json
import base64

API_KEY = "CDl4l8Q31uSMQy3Eut0lKkvF"
SECRET_KEY = "vc7stR4tRA974ToL0q351zCnzyAHpDkV"


def main(image1_path, image2_path):
    url = "https://aip.baidubce.com/rest/2.0/face/v3/match?access_token=" + get_access_token()

    image1_base64 = encode_image(image1_path)
    image2_base64 = encode_image(image2_path)

    payload = json.dumps([
        {"image": image1_base64, "image_type": "BASE64"},
        {"image": image2_base64, "image_type": "BASE64"}
    ])
    headers = {'Content-Type': 'application/json'}

    response = requests.request("POST", url, headers=headers, data=payload)
    result = json.loads(response.text)
    
    if 'result' in result and 'score' in result['result']:
        return result['result']['score']
    else:
        return None


def encode_image(image_path):
    with open(image_path, "rb") as file:
        return str(base64.b64encode(file.read()), encoding="utf-8")


def get_access_token():
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
    return str(requests.post(url, params=params).json().get("access_token"))


def choose_image(label):
    filename = filedialog.askopenfilename()
    label.config(text=filename)


def compare_images():
    image1_path = label1.cget("text")
    image2_path = label2.cget("text")
    image3_path = label3.cget("text")
    
    if image1_path and image2_path and image3_path:
        score1 = main(image1_path, image2_path)
        score2 = main(image1_path, image3_path)
        
        if score1 is not None and score2 is not None:
            highest_score = max(score1, score2)
            
            if highest_score == score1:
                result_label.config(text=f"Highest Score: {highest_score}\n照片与Photo 1更匹配哦")
            else:
                result_label.config(text=f"Highest Score: {highest_score}\n照片与Photo 2更匹配哦")
        else:
            result_label.config(text="Error occurred during comparison.")
    else:
        result_label.config(text="Please select images for comparison.")


app = tk.Tk()
app.title("Face Comparison App")

label1 = tk.Label(app, text="No image selected.")
label1.grid(row=0, column=0, padx=10, pady=5)

label2 = tk.Label(app, text="No image selected.")
label2.grid(row=1, column=0, padx=10, pady=5)

label3 = tk.Label(app, text="No image selected.")
label3.grid(row=2, column=0, padx=10, pady=5)

browse_button1 = tk.Button(app, text="Select Your Photo", command=lambda: choose_image(label1))
browse_button1.grid(row=0, column=1, padx=10, pady=5)

browse_button2 = tk.Button(app, text="Select Comparison Photo 1", command=lambda: choose_image(label2))
browse_button2.grid(row=1, column=1, padx=10, pady=5)

browse_button3 = tk.Button(app, text="Select Comparison Photo 2", command=lambda: choose_image(label3))
browse_button3.grid(row=2, column=1, padx=10, pady=5)

compare_button = tk.Button(app, text="Compare Images", command=compare_images)
compare_button.grid(row=3, column=0, columnspan=2, padx=10, pady=5)

result_label = tk.Label(app, text="")
result_label.grid(row=4, column=0, columnspan=2, padx=10, pady=5)

app.mainloop()